package com.tajiang.business.common.application;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.Application;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.gprinter.aidl.GpService;
import com.gprinter.service.GpPrintService;
import com.igexin.sdk.PushManager;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;
import com.tajiang.business.R;
import com.tajiang.business.common.constant.TJCst;
import com.tajiang.business.common.dialog.DialogWithOneButton;
import com.tajiang.business.common.retrofit.cookieJar.ClearableCookieJar;
import com.tajiang.business.common.retrofit.cookieJar.PersistentCookieJar;
import com.tajiang.business.common.retrofit.cookieJar.cache.SetCookieCache;
import com.tajiang.business.common.retrofit.cookieJar.persistence.SharedPrefsCookiePersistor;
import com.tajiang.business.common.retrofit.ssl.TJSSLUtil;
import com.tajiang.business.common.utils.CommandTools;
import com.tajiang.business.common.utils.CommonUtils;
import com.tajiang.business.common.utils.LogUtils;
import com.tajiang.business.common.utils.SharedPreferencesUtils;
import com.taobao.sophix.PatchStatus;
import com.taobao.sophix.SophixManager;
import com.taobao.sophix.listener.PatchLoadStatusListener;

import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;


public class TJApp extends Application {
    /**
     * 应用程序包名
     */
    public static final String MY_PKG_NAME = "com.tajiang.business";
    /**
     * 登录用户的权限
     */
    public static final int RULES_ADMIN = 1;
    public static final int RULES_SCHOOL_MANAGER = 2;
    public static final int RULES_SCHOOL_CEO = 3;
    public static final int RULES_LOU_ZHANG = 4;

    private List<Activity> activities = new ArrayList<>();

    private OkHttpClient okHttpClient;
    private volatile static TJApp app;
    private RefWatcher refWatcher;
    private GpService mGpService = null;
    private PrinterServiceConnection conn = null;

    public static boolean new_order_noice = false;//新订单声音

    public GpService getmGpService() {
        return mGpService;
    }

    class PrinterServiceConnection implements ServiceConnection {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            LogUtils.i("ServiceConnection", "onServiceDisconnected() called");
            mGpService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mGpService = GpService.Stub.asInterface(service);
        }
    }

    /**
     * 是否已经显示登陆界面
     */
    private volatile boolean isShowLogin;

    public boolean isShowLogin() {
        return isShowLogin;
    }

    public void setShowLogin(boolean showLogin) {
        isShowLogin = showLogin;
    }

    public static RequestQueue mRequestQueue;
    public long limitTime;
    public String sendTime = "35916884898255966"; // 加密time
    public String mToken;

    protected static ImageLoader imageLoader = ImageLoader.getInstance();
    protected static DisplayImageOptions options; // DisplayImageOptions是用于设置图片显示的类

    @Override
    public void onCreate() {
        super.onCreate();
        app = this;
        initdata();                                 //初始化APP配置文件参数
        initHttpClient();
        initPrintServiceConnection();               //初始化蓝牙打印服务
        initPushManager();                          //初始化个推推送服务
        Fresco.initialize(getApplicationContext()); // 加载网络图片
//        initHotfix();                               //热修复初始化
        if (TJCst.IS_LEAK_CANARY_OPEN) {            //初始化内存泄漏侦测工具
            initLeakCanary();
        }

        mRequestQueue = Volley.newRequestQueue(this);
        mRequestQueue.start();

        new_order_noice = (boolean) SharedPreferencesUtils.get(SharedPreferencesUtils.AUDIO_ATTENTION, false);
        initImageLoader();
    }

    public static RequestQueue getQueue(){

        if(mRequestQueue == null){
            mRequestQueue = Volley.newRequestQueue(app);
        }

        return mRequestQueue;
    }

    private void initLeakCanary() {
        if (LeakCanary.isInAnalyzerProcess(this)) {
            // This process is dedicated to LeakCanary for heap analysis.
            // You should not init your app in this process.
            return;
        }
        refWatcher = LeakCanary.install(this);
        // Normal app init code...
    }

    private void initdata() {
        //初始化自动打印参数
        if (! SharedPreferencesUtils.contains(SharedPreferencesUtils.AUTO_PRINT)) {
            SharedPreferencesUtils.put(SharedPreferencesUtils.AUTO_PRINT, true);
        }
        //初始化语音提示参数
        if (! SharedPreferencesUtils.contains(SharedPreferencesUtils.AUDIO_ATTENTION)) {
            SharedPreferencesUtils.put(SharedPreferencesUtils.AUDIO_ATTENTION, true);
        }
        //初始化是否已上传用户ClientID及相关数据  false --> 未上传
        if (! SharedPreferencesUtils.contains(SharedPreferencesUtils.BOOLEAN_CID_COLLECTED)) {
            SharedPreferencesUtils.put(SharedPreferencesUtils.BOOLEAN_CID_COLLECTED, false);
        }
    }

    /**
     * 初始化OkHttpClient
     */
    private void initHttpClient() {
        ClearableCookieJar cookieJar = new PersistentCookieJar(
                new SetCookieCache(),
                new SharedPrefsCookiePersistor(TJApp.getInstance()));
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        //自定义 OKHttpClient 客户端
        okHttpClient = new OkHttpClient.Builder()
                .sslSocketFactory(TJSSLUtil.getSSLSocketFactory())// 添加对 HTTPS 的支持
                .addInterceptor(interceptor)
                .cookieJar(cookieJar)
                .build();
    }

    public synchronized OkHttpClient getOkHttpClient() {
        if (okHttpClient == null) {
            initHttpClient();
        }
        return okHttpClient;
    }

    private void initPrintServiceConnection() {
        conn = new PrinterServiceConnection();
        Intent intent = new Intent(this, GpPrintService.class);
        bindService(intent, conn, Context.BIND_AUTO_CREATE); // bindService
    }

    private void initPushManager() {
        PushManager.getInstance().initialize(this.getApplicationContext());
    }

    public static TJApp getInstance() {
        return app;
    }

    public RefWatcher getRefWatcher() {
        return refWatcher;
    }

    /**
     * 新建了一个activity
     * @param activity
     */
    public void addActivity(Activity activity) {
        if(activity != null) {
            activities.add(activity);
        }
    }
    /**
     *  结束指定的Activity
     * @param activity
     */
    public void finishActivity(Activity activity) {
        if (activity!=null) {
            this.activities.remove(activity);
            activity.finish();
        }
    }

    /**
     * 结束指定的Activity(通过类名)
     */
    public void finishActivity(Class clazz) {
        for (Activity activity : activities) {
            if (activity != null && activity.getClass().equals(clazz)) {
                this.activities.remove(activity);
                activity.finish();
            }
        }
    }
    /**
     * 应用退出，结束所有的activity
     */
    public void exit(){
        for (Activity activity : activities) {
            if (activity!=null) {
                activity.finish();
            }
        }
//        if (conn != null) {
//            unbindService(conn); // unBindService
//        }
        System.exit(0);
    }


    /**
     * 初始化ImageLoader
     */
    private void initImageLoader() {

        // 如果上一次删除文件不是今天，则删除文件
//        if (!SharedPreferencesUtils.getParam(Constant.SP_DELETE_FILE_DAY, "")
//                .equals(CommandTools.getChangeDate(-7))) {
//
//            FileUtils.deleteDir(Constant.cacheDir.toString());
//            SharedPreferencesUtils.setParam(Constant.SP_DELETE_FILE_DAY,
//                    CommandTools.getChangeDate(-7));
//        }

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                this).threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .discCache(new UnlimitedDiscCache(CommonUtils.cacheDir))
                // 缓存路径
                .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
                .build();// 开始构建
        ImageLoader.getInstance().init(config);
    }

    /**
     * 多张图片加载处理
     *
     * @return
     */
    public static ImageLoader getImageLoader() {

        if (imageLoader == null) {
            imageLoader = ImageLoader.getInstance();
        }

        return imageLoader;
    }

    /**
     * 图片加载
     *
     * @return
     */
    public DisplayImageOptions getOptions() {

        if (options == null) {
            options = new DisplayImageOptions.Builder()
                    // .showStubImage(R.drawable.male)// 设置图片下载期间显示的图片 ，暂时去掉这个属性
                    .showImageForEmptyUri(R.drawable.ic_launcher) // 设置图片Uri为空或是错误的时候显示的图片
                    .showImageOnFail(R.drawable.ic_launcher) // 设置图片加载或解码过程中发生错误显示的图片
                    .cacheInMemory().cacheOnDisc()// 下载的图片缓存在内存卡中
                    .bitmapConfig(Bitmap.Config.RGB_565).build();
        }

        return options;
    }

    /**
     * 图片加载、加载失败则不显示图片
     *
     * @return
     */
    public static DisplayImageOptions getOptionsErrorPic() {

        if (options == null) {
            options = new DisplayImageOptions.Builder()
                    // .showStubImage(R.drawable.male)// 设置图片下载期间显示的图片 ，暂时去掉这个属性
                    .showImageForEmptyUri(R.drawable.ic_launcher) // 设置图片Uri为空或是错误的时候显示的图片
                    .showImageOnFail(R.drawable.ic_launcher) // 设置图片加载或解码过程中发生错误显示的图片
                    .cacheInMemory().cacheOnDisc()// 下载的图片缓存在内存卡中
                    .bitmapConfig(Bitmap.Config.RGB_565).build();
        }

        return options;
    }

    /*
    * 热修复初始化
     **/
    private void initHotfix() {

        String appVersion;
        try {
            appVersion = this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName;
        } catch (Exception e) {
            appVersion = "1.1.0";
        }

        SophixManager.getInstance().setContext(this)
                .setAppVersion(appVersion)
                .setAesKey(null)
                //.setAesKey("0123456789123456")
                .setEnableDebug(true)
                .setPatchLoadStatusStub(new PatchLoadStatusListener() {
                    @Override
                    public void onLoad(final int mode, final int code, final String info, final int handlePatchVersion) {

                        Message message = new Message();
                        String msg = "";

                        // 补丁加载回调通知
                        if (code == PatchStatus.CODE_LOAD_SUCCESS) {
                            // 表明补丁加载成功
                            msg =  "热修复成功";
                            message.what = 0x0001;
                            message.obj = msg;
                            mHandler.sendMessage(message);
                        } else if (code == PatchStatus.CODE_LOAD_RELAUNCH) {
                            // 表明新补丁生效需要重启. 开发者可提示用户或者强制重启;
                            // 建议: 用户可以监听进入后台事件, 然后应用自杀
                            msg = "热修复加载完成，生效需要重启";
                            message.what = 0x0002;
                            message.obj = msg;
                            mHandler.sendMessage(message);
                        } else if (code == PatchStatus.CODE_LOAD_FAIL) {
                            // 内部引擎异常, 推荐此时清空本地补丁, 防止失败补丁重复加载
                            SophixManager.getInstance().cleanPatches();
                        } else {
                            // 其它错误信息, 查看PatchStatus类说明
//                            msg = "onLoad: 其它错误信息" + code + "/" + msg;
                        }

                    }
                }).initialize();

        SophixManager.getInstance().queryAndLoadNewPatch();
    }

    public void restartApp(){

        DialogWithOneButton.showDialog(CommandTools.getGlobalActivity(), "重启", "修复成功，重启生效", new DialogWithOneButton.DialogCallback() {

            @Override
            public void callback(int position) {

                Intent intent = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
                PendingIntent restartIntent = PendingIntent.getActivity(CommandTools.getGlobalActivity(), 0, intent, PendingIntent.FLAG_ONE_SHOT);
                AlarmManager mgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
                mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 500, restartIntent); // 1秒钟后重启应用

                exit();
            }
        });

    }

    public Handler mHandler = new Handler(){

        public void handleMessage(Message msg){

            if(msg.what == 0x0001){

//                ToastUtils.showShort((String) msg.obj);
            }else if(msg.what == 0x0002){
                restartApp();
            }

        }
    };
}
